#!/usr/bin/python
# -*- coding: UTF-8 -*-
#运行文件 人工智能.py
#作者 幽灵代码
#QQ 29672366
#邮箱 29672366@qq.com
#日期 2020.10.5

import sys
import os

rootpath = os.getcwd()
corename = 'core'
libname = 'lib'


import sqlite3 as db
import modelparse
import re
import baidubaike as baike

#加载数据库
cx=db.connect(rootpath+"/db/data.db",check_same_thread = False)
cu=cx.cursor()


character = {}
character['出生日期'] = ''
character['昵称'] = ''
character['中文名'] = ''
character['英文名'] = ''
character['年龄'] = ''
character['性别'] = ''
character['身高'] = ''
character['职业'] = ''
character['位置'] = ''
character['状态'] = ''
character['错误消息'] = ''


me = {}
me['出生日期'] = '(这也许是个秘密)'
me['昵称'] = '蜜儿'
me['中文名'] = '蜜儿'
me['英文名'] = 'Mia'
me['年龄'] = '18'
me['性别'] = '女'
me['身高'] = '167'
me['职业'] = '秘书'
me['位置'] = ''
me['状态'] = ''
me['错误消息'] = ''

import datetime
import aitime.aitime as aitime

def calculate_age(birth_s='20201007'):
    birth_d = datetime.datetime.strptime(birth_s, "%Y%m%d")
    today_d = datetime.datetime.now()
    birth_t = birth_d.replace(year=today_d.year)
    if today_d > birth_t:
        age = today_d.year - birth_d.year
    else:
        age = today_d.year - birth_d.year - 1
    return age

def loadCharacter(name):
    global character
    if(name.strip()=='你'):
        character = me.copy()
        return True
    elif(name.strip()=='他' or name.strip()=='她'):
        if character['中文名'] != '':
            return True
    #text = bzd.baidu_search(name+'出生于')
    text = baike.searchbaike(name)
    if(text !=''):
        result = aitime.getTimeDict(text)
        if '错误消息' not in  result:
            character['中文名'] = name
            age = calculate_age(result['年']+result['月']+result['日'])
            if age == 0:
                character['错误消息'] = '"'+name+'"我好像没查到'
            else:
                character['年龄'] = str(age)
                character['出生日期'] = result['年']+'年'+result['月']+'月'+result['日']+'日'
        
        return True
    return False

def isCharacter(name):
    return loadCharacter(name)

def getCharacter(text):
    text = ' '+text
    character['错误消息'] = ''
    #加载历史数据或者实时爬取
    explst = [
        '([\u4e00-\u9fa5A-Za-z ]+?)?[(?:什么)叫他她哪是的].*?(?:名字|中文名|生日|出生的|生的|出生日期)', #0
        '([\u4e00-\u9fa5A-Za-z ]+(?<!现在))?(?:现在|有)?(?:多大)',#1 不以XX结尾(?<!XX) 不以XX开头(?!XX)
        '([\u4e00-\u9fa5A-Za-z ]+(?<!现在))?(?:现在|有)?(?:多高)',#2
        '([\u4e00-\u9fa5A-Za-z ]+)?(?:现在)?(?:在)?(?:哪|干嘛|做什么)',#3
    ]
    errormsg = ''
    for index in range(0,len(explst)):
        exp = re.compile(explst[index])
        textlist = exp.findall(text)
        if len(textlist) == 0:
          continue
        #print(textlist)
        #print(index)
        name = textlist[0]
        if(name!=''):
            if isCharacter(name)==False and character['中文名']=='':
                character['错误消息'] = '我不知道你说的是谁'
        break
    return character


